<script setup>
	// import { io } from 'socket.io-client'
	import io  from '@hyoga/uni-socket-io'

	import { ref, computed, nextTick } from 'vue'
	import PatientInfo from './components/patient-info.vue'
	import NotifyInfo from './components/notify-info.vue'
	import MessageInfo from './components/message-info.vue'
	import PrescriptionInfo from './components/prescription-info.vue'
	import RateInfo from './components/rate-info.vue'
	import RoomStatus from './components/room-status.vue'
	import { useUserStore } from '@/stores/user.js'
	import { patientDetailApi, orderListApi } from '@/services/consult.js'
	import dayjs from 'dayjs'
	const { windowHeight, statusBarHeight } = uni.getSystemInfoSync()

	// 问诊订单详情
	const orderDetail = ref({})
	const { token, userId } = useUserStore()
	const props = defineProps({
		orderId: String, // 支付id，也是诊室订单id
	})
	const inputMsg = ref('')
	const messageList = ref([])
	const refreshTrigger = ref(true)
	const lastTime = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
	const scrollViewRef = ref(null)
	const scrollIntoView = ref('')
	
	// 滚动到底部
	async function scrollToBottom() {
		await nextTick()
		if (messageList.value.length > 0) {
			scrollIntoView.value = `msg-${messageList.value[messageList.value.length - 1].id}`
		}
	}

	// 获取订单列表
	async function getOrderList() {
		// 获取订单列表
		const { code, data, message } = await orderListApi({
			current: 1,
			pageSize: 10,
			type: 1, // 问诊订单
			status: 1 // 待接诊
		})
		
		if (code !== 10000) return uni.utils.toast(message)
		
		// 如果有待接诊的订单，跳转到对应的诊室
		if (data.rows.length > 0) {
			uni.navigateTo({
				url: `/subpkg_consult/room/index?orderId=${data.rows[0].id}`
			})
		} else {
			// 没有待接诊订单，跳转到咨询页面
			uni.navigateTo({
				url: '/pages/consult/index'
			})
		}
	}

	// 继续咨询
	async function continueConsult() {
		await getOrderList()
	}

	// 建立连接
	const socket = io('https://consult-api.itheima.net', {
		auth: { token: 'Bearer ' + token },
		query: { orderId: props.orderId },
		transports: ['websocket', 'polling'],
		timeout: 5000,
	})

	// 获取历史数据:刷新等
	socket.on('chatMsgList', ({ code, data, message }) => {
		refreshTrigger.value = false

		if (code !== 10000) return
		const tempList = []
		data.forEach(({ createTime, items }, index) => {
			if (index === 0) lastTime.value = createTime
			// 追加到消息列表中
			tempList.push(
				{
					msg: {
						content: createTime,
					},
					msgType: 31, //普通消息31
					id: createTime,
				},
				...items
			)
		})
		// 是否获取到新数据
		if (tempList.length === 0) return uni.utils.toast('没有更多聊天记录了')
		// 追加到消息列表中
		messageList.value.unshift(...tempList)
	})

	// 监听接收消息：即时聊天消息
	socket.on('receiveChatMsg', (message) => {
		// 修改消息为已读
		socket.emit('updateMsgStatus', message.id)
		messageList.value.push(message)
		scrollToBottom()
	})

	// 监听订单变化
	socket.on('statusChange', (data) => {
		orderDetail.value = data
	})

	// 下拉刷新
	function refresherrefresh() {
		// 开启下拉交互动画
		refreshTrigger.value = true
		// 获取历史前20条消息
		socket.emit('getChatMsgList', 20, lastTime.value, props.orderId)
	}

	// 获取问诊订单详情
	async function getPatientDetail() {
		// 调用接口
		const { code, data, message } = await patientDetailApi(props.orderId)
		// 检测接口是否调用成功
		if (code !== 10000) return uni.utils.toast(message)
		// 渲染问诊订单数据
		orderDetail.value = data
	}

	getPatientDetail()

	async function inputConfirm(msg) {
		// 发送消息
		socket.emit('sendChatMsg', {
			from: userId,
			to: orderDetail.value.docInfo?.id,
			msgType: 1,
			msg: {
				content: msg,
			},
		})
		inputMsg.value = ''
		await nextTick()
		scrollToBottom()
	}

	// 上传图片
	async function uploadImg() {
		if (orderDetail.value.status !== 3)
			return uni.utils.toast('医生当前不在线!')
		uniCloud.chooseAndUploadFile({
			count: 1,
			type: 'image',
			extension: ['.jpg', '.png', '.gif'],
			success: (res) => {
				const picture = {
					url: res.tempFiles[0].url,
					id: res.tempFiles[0].lastModified,
				}
				socket.emit('sendChatMsg', {
					from: userId,
					to: orderDetail.value.docInfo?.id,
					msgType: 4,
					msg: {
						content: picture,
					},
				})
				scrollToBottom()
			},
		})
	}
</script>

<template>
	<view class="room-page">
		<RoomStatus
			:statusValue="orderDetail.statusValue"
			:status="orderDetail.status"
			:countdown="orderDetail.countdown"
			@tab-change="getOrderList"
		></RoomStatus>
		<scroll-view
			ref="scrollViewRef"
			scroll-y
			refresher-enabled
			:refresher-triggered="refreshTrigger"
			@refresherrefresh="refresherrefresh"
			refresher-background="#f2f2f2"
			:scroll-into-view="scrollIntoView"
			:style="{ height: `calc(100vh - ${statusBarHeight + 44}px - 100rpx)` }"
		>
			<view class="scroll-page-content">
				<view class="message-container">
					<template v-for="message in messageList" :key="message.id">
						<view :id="`msg-${message.id}`">
							<!-- 患者信息（21） -->
							<PatientInfo
								v-if="message.msgType === 21"
								:info="message.msg.consultRecord"
							></PatientInfo>
							<!-- 通知信息(>=31) -->
							<NotifyInfo
								v-if="message.msgType >= 31"
								:type="message.msgType"
								:msg="message.msg.content"
							>
							</NotifyInfo>
							<!--医生信息(1,4) -->
							<MessageInfo
								v-if="message.msgType <= 4"
								:info="message"
								:type="message.msgType"
								:from="userId"
							></MessageInfo>
							<!--处方信息(22) -->
							<PrescriptionInfo
								v-if="message.msgType === 22"
								:info="message.msg.prescription"
							></PrescriptionInfo>
							<!--评价信息(23) -->
							<RateInfo
								v-if="message.msgType === 23"
								:orderId="props.orderId"
								:doctorId="orderDetail.docInfo.id"
								:hasEvaluate="false"
							>
							</RateInfo>

							<!--评价信息(24) -->
							<RateInfo
								v-if="message.msgType === 24"
								:score="message.msg.evaluateDoc.score"
								:content="message.msg.evaluateDoc.content"
								:hasEvaluate="true"
							>
							</RateInfo>
						</view>
					</template>
				</view>
			</view>
		</scroll-view>

		<!-- 发送消息 -->
		<view class="message-bar">
			<view class="contact" v-if="orderDetail.status === 3">
				<uni-easyinput
					:disabled="orderDetail.status !== 3"
					:input-border="false"
					:clearable="false"
					v-model="inputMsg"
					placeholder="问医生"
					placeholder-style="font-size: 32rpx; color: #c3c3c5;padding: 0 30rpx;"
					@confirm="inputConfirm"
				/>
				<uni-icons type="image" size="30" @click="uploadImg"></uni-icons>
			</view>
			<view v-else class="continue-consult">
				<button class="uni-button" @click="continueConsult">继续咨询</button>
			</view>
		</view>
	</view>
</template>

<style lang="scss">
	.room-page {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f2f2f2;
		
		.scroll-page-content {
			padding-bottom: 100rpx;
		}
		
		.message-container {
			padding: 10rpx 30rpx;
			overflow: hidden;
		}
		
		.message-bar {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			box-sizing: border-box;
			height: 130rpx;
			padding: 20rpx 30rpx;
			padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
			background-color: #fff;
			z-index: 100;
			
			.contact {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 100%;
				
				:deep(.uni-input-wrapper) {
					flex: 1;
					box-sizing: border-box;
					border-radius: 40rpx !important;
					background-color: #f6f6f6;
					padding-left: 30rpx !important;
					margin-right: 20rpx;
					height: 72rpx;
				}
				
				:deep(.is-disabled) {
					background-color: transparent !important;
				}
				
				:deep(.uniui-image) {
					color: #949494 !important;
					padding: 10rpx;
				}
			}
			
			.continue-consult {
				display: flex;
				justify-content: center;
				align-items: center;
				height: 100%;
				
				.uni-button {
					width: 100%;
					height: 72rpx;
					line-height: 72rpx;
					background-color: #16c2a3;
					color: #fff;
					border-radius: 40rpx;
					font-size: 32rpx;
					
					&:active {
						opacity: 0.8;
					}
				}
			}
		}
	}
</style>
